﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;

/// <summary>
/// StringUtil 的摘要说明
/// </summary>
public class StringUtil
{
	public StringUtil()
	{
		//
		// TODO: 在此处添加构造函数逻辑
		//
	}

    public static string SubString(string content, int length)
    {

        System.Text.StringBuilder sb = null;
        try
        {
            sb = new System.Text.StringBuilder();
            System.Text.Encoding encoding = System.Text.Encoding.GetEncoding("gb2312");
            int totalLength = 0;
            foreach (char contentChar in content)
            {
                int size = encoding.GetByteCount(new char[] { contentChar }); //获得1或2，中文2，英文1
                if (totalLength + size > length - 2)
                {
                    sb.Append("...");
                    break;
                }
                sb.Append(contentChar);
                totalLength += size;
            }
        }
        catch
        {
            sb.Append("");
        }
        return sb.ToString();
    }
    /// <summary>
    /// 去掉html
    /// </summary>
    /// <param name="strHtml"></param>
    /// <returns></returns>
    public static string StripHTML(string strHtml)
    {
        string[] aryReg ={
        @"<script[^>]*?>.*?</script>",
        @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
        @"([\r\n])[\s]+",
        @"&(quot|#34);",
        @"&(amp|#38);",
        @"&(lt|#60);",
        @"&(gt|#62);",
        @"&(nbsp|#160);",
        @"&(iexcl|#161);",
        @"&(cent|#162);",
        @"&(pound|#163);",
        @"&(copy|#169);",
        @"&#(\d+);",
        @"-->",
        @"<!--.*\n"
        };
        string[] aryRep =   {
        "",
        "",
        "",
        "\"",
        "&",
        "<",
        ">",
        "   ",
        "\xa1",//chr(161),   
                                "\xa2",//chr(162),   
                                "\xa3",//chr(163),   
                                "\xa9",//chr(169),   
                                "",
        "\r\n",
        ""
        };
        string newReg = aryReg[0];
        string strOutput = strHtml;
        strOutput = strOutput.Replace("&nbsp;", "");
        for (int i = 0; i < aryReg.Length; i++)
        {
            Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
            strOutput = regex.Replace(strOutput, aryRep[i]);
        }
        strOutput=strOutput.Replace("<", "");
        strOutput = strOutput.Replace(">", "");
        strOutput = strOutput.Replace("\r\n", "");
        strOutput = strOutput.Replace(" ", "");
        return strOutput;
    }
}
